<template>
  <div class="page-wrap page-login">
    <van-loading vertical v-if="loading">
      <template #icon></template>
      <vue3-lottie :animationData="loadingImg" :width="100" />
      系统登录中...
    </van-loading>
  </div>
</template>
<script setup>
import loadingImg from '@/assets/json/animataion/loading.json';
import { onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { isLogin, setToken, clearToken } from '@/utils/auth';
import { userService } from '@/api/user-service';
import { useUserStore } from '@/store';
import CONFIG from '@/config/config';
import { tools } from '@/utils/tools';
import useLoading from '@/hooks/loading';
const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const { loading, setLoading } = useLoading(true);
const appId = 'cli_a6a7098f1f2d100b'; //正式
const token = route.query.token;
const code = route.query.code;
let key = 'zhishu';
let redirect = route?.query?.path || route?.query?.redirect || '';
let query = { ...route.query };
// 删除特定的字符
if (query?.code) {
  delete query.code;
}
if (query?.token) {
  delete query.token;
}
if (query?.key) {
  delete query.key;
}
if (code) {
  query = JSON.parse(decodeURIComponent(route?.query?.state));
  redirect = query?.path || query?.redirect || '';
}
if (key) {
  tools.setCookie(CONFIG.KEY, key, 365);
  clearToken();
} else {
  key = tools.getCookie(CONFIG.KEY);
}

// 跳转
const goHome = () => {
  //   console.log('2922222', redirect, query);
  if (redirect) {
    // console.log(59, redirect, query);
    delete query.path;
    delete query.redirect;
    router.push({ path: redirect, query });
    return;
  }
  router.push({ name: 'home-index' });
};

const feishuLogin = () => {
  const target = `https://open.feishu.cn/open-apis/authen/v1/index?app_id=${appId}&redirect_uri=${encodeURIComponent(location.origin + location.pathname)}&state=${encodeURIComponent(JSON.stringify(query))}`;
  window.location.replace(target);
};
// 拿到code值后调登录接口
const logins = () => {
  userService
    .login({ code, key: key || import.meta.env.VITE_KEY })
    .then(async (res) => {
      if (!res.error) {
        setToken(res.result?.token);
        await userStore.getUserinfo();
        goHome();
      } else if (res.error?.code === 10051) {
        feishuLogin();
      } else {
        //
        console.log(res.error);
      }
    })
    .catch((err) => {
      console.log(err);
    });
};
// 获取用户信息

if (isLogin()) {
  console.log(111, 'login');
  goHome();
} else if (token) {
  setToken(token);
  //跳转入首页
  goHome();
} else {
  // window.location.href = `http://sso.xiaolutg.com/?redirect_uri=${location.origin}/login`;
  if (code) {
    logins();
  } else {
    feishuLogin();
  }
}

// onBeforeUnmount
onBeforeUnmount(() => {
  setLoading(false);
});
</script>
<style scoped lang="less">
@import './login.less';
</style>
